<?php

namespace Apps\AppApi\Method\User;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\Question;
use Apps\Common\Models\QuestionAnswer;
use Apps\Common\Models\QuestionFollow;
use PhalconPlus\Api\Common\ResultStatus;
use Phalcon\Mvc\Model\Resultset\Simple as ResultSet;


/**
 * 他的问答列表
 * @package Apps\AppApi\Method\User
 */
class HisQuestionList extends BaseMethod
{
    public function run()
    {
        $his_id = $this->getDataItem('his_id');//要查询用户的id
        $type = $this->getDataItem('type', '');
        $page = intval($this->getDataItem('page',1));
        /**
         * 验证用户权限
         */
        if(!empty($this->parameters->userToken) && true == $this->verifyUserAuth()){
            if ($this->getUserAuth()->userId == $his_id){
                return $this->errorLog(111, '请跳转我的问答.');;
            }
        }
        $limit = $this->getConfig()->limit;
        $offset = ($page-1) * $limit;

        $typeArray = ['his', 'his_answer', 'his_follow'];
        if(!in_array($type, $typeArray)) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '查询的类型不存在.');
        }

        $columns = [
            'u.user_id',
            'u.user_nickname',
            'u.user_cover',
            'Apps\Common\Models\Question.question_id question_id',
            'Apps\Common\Models\Question.question_content question_content',
            'Apps\Common\Models\Question.question_pics question_pics',
            'Apps\Common\Models\Question.answer_num answer_num',
            'Apps\Common\Models\Question.question_browsers browser_num',
            'Apps\Common\Models\Question.question_follows follow_num',
            'Apps\Common\Models\Question.question_addtime addtime'
        ];
        $userId = $his_id;

        $data = [];
        switch($type) {
            case 'his':
                $data = $this->getHis($userId, $columns, $limit, $offset);
                break;
            case 'his_answer':
                $data = $this->getAnswer($userId, $limit, $offset);
                break;
            case 'his_follow':
                $data = $this->getFollow($userId, $columns, $limit, $offset);
                break;
        }
        $result = [];
        if($data && count($data) > 0) {
            foreach ($data as $arr) {
                
                $tmp = PicUrl::Question(json_decode($arr['question_pics']), $this->getDi());
               
                if(is_string($tmp)) {
                   $arr['question_pics'] = $tmp;
                }
                if(is_array($tmp)) {
                    $arr['question_pics'] = array_slice($tmp,0,2);
                }
                //$arr['addtime'] = \Apps\Common\Libs\DateTime::Format($arr['addtime']);
                $arr['user_cover'] = PicUrl::UserCover($arr['user_cover'], $this->getDi());
                if(unserialize(base64_decode($arr['question_content']))){
                    $arr['question_content'] = unserialize(base64_decode($arr['question_content']));
                }
                $result[] = $arr;
            }
        }
        $this->setResult($result);
    }

    private function getHis($userId, $columns, $limit, $offset)
    {
        return Question::query()
            ->columns($columns)
            ->leftJoin('Apps\Common\Models\UserBase',
                'Apps\Common\Models\Question.user_id = u.user_id','u')
            ->where('question_state > 0 AND Apps\Common\Models\Question.user_id=:user_id:')
            ->bind(['user_id' => $userId])
            ->orderBy('question_id desc')
            ->limit($limit, $offset)
            ->execute()->toArray();
    }

    private function getAnswer($userId, $limit, $offset)
    {
        $sql = <<<SQL
SELECT
	u.user_id AS user_id,
	u.user_nickname AS user_nickname,
	u.user_cover AS user_cover,
	question.question_id AS question_id,
	question.question_content AS question_content,
	question.question_pics AS question_pics,
	question.answer_num AS answer_num,
	question.question_browsers AS browser_num,
	question.question_follows AS follow_num,
	question.question_addtime AS addtime
FROM question_answer AS qa
LEFT JOIN question ON question.question_id = qa.question_id
LEFT JOIN user_base AS u ON question.user_id = u.user_id
WHERE question.question_state > 0 AND qa.user_id = :uid
GROUP BY question.question_id
ORDER BY question_id DESC
LIMIT $limit OFFSET $offset
SQL;
        $model = new QuestionAnswer();
        $result = new ResultSet(
            null,
            $model,
            $model->getReadConnection()->query($sql, ['uid' => $userId])
        );
        return $result->toArray();
    }

    private function getFollow($userId, $columns, $limit, $offset)
    {
        return QuestionFollow::query()
            ->columns($columns)
            ->leftJoin('Apps\Common\Models\Question',
                'Apps\Common\Models\Question.question_id = Apps\Common\Models\QuestionFollow.question_id')
            ->leftJoin('Apps\Common\Models\UserBase',
                'Apps\Common\Models\Question.user_id = u.user_id','u')
            ->where('question_state > 0 AND Apps\Common\Models\QuestionFollow.user_id = :user_id:')
            ->bind(['user_id' => $userId])
            ->orderBy('question_id desc')
            ->limit($limit, $offset)
            ->execute()->toArray();
    }
}